package hunglv.android.rss;

import hunglv.android.rss.entities.RSSFeed;
import hunglv.android.rss.handler.RSSHandler;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.os.AsyncTask;
import android.os.Message;

public class FeedRSSAsyncTask extends AsyncTask<String, Void, Void>{
	private RSSFeed feed;
	
	public FeedRSSAsyncTask(){
		feed = new RSSFeed();
	}
	
	@Override
	protected Void doInBackground(String... params) {
		String urlToRssFeed = params[0];
		
		feed = getFeed(urlToRssFeed);
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result){
		Message msg = new Message();
		msg.what = MainActivity.NOTIFY_FINISH;
		MainActivity.mHandler.sendMessage(msg);
	}
	
	private RSSFeed getFeed(String urlToRssFeed){
		try{
			URL url = new URL(urlToRssFeed);
			
			SAXParserFactory mFactory = SAXParserFactory.newInstance();
			SAXParser mParser = mFactory.newSAXParser();
			XMLReader mReader = mParser.getXMLReader();
			RSSHandler mHandler = new RSSHandler();
			
			mReader.setContentHandler(mHandler);
			
			InputSource input = new InputSource(url.openStream());
			mReader.parse(input);
			
			return mHandler.getFeed();
		}catch(FactoryConfigurationError e){
			e.printStackTrace();
		}catch(ParserConfigurationException e){
			e.printStackTrace();
		}catch(SAXException e){
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public RSSFeed getFeed() {
		return feed;
	}
}
